package com.programmercarl.stackandqueue;

import java.util.*;

/**
 * https://leetcode.cn/problems/evaluate-reverse-polish-notation/description/
 *
 * @author yulongtian
 * @create 2024-12-16 10:20
 */
public class Test02 {
    public static void main(String[] args) {
//        String[] tokens = {"2", "1", "+", "3", "*"};
        String[] tokens = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
//        String[] tokens = {"4", "13", "5", "/", "+"};
        System.out.println(evalRPN(tokens));
    }

    public static int evalRPN(String[] tokens) {
        int res = 0;
        Deque<String> stack_num = new ArrayDeque<>();
        List<String> operations = new ArrayList<>(4);
        operations.add("+");
        operations.add("-");
        operations.add("*");
        operations.add("/");
        for (String token : tokens) {
            // 是运算符，数栈出两个数，并运算，再存入数栈
            if (operations.contains(token)) {
                int num2 = Integer.parseInt(stack_num.pop());
                int num1 = Integer.parseInt(stack_num.pop());
                switch (token) {
                    case "+":
                        res = num1 + num2;
                        break;
                    case "-":
                        res = num1 - num2;
                        break;
                    case "*":
                        res = num1 * num2;
                        break;
                    case "/":
                        res = num1 / num2;
                        break;
                }
                stack_num.push(String.valueOf(res));
            } else {
                // 是整数，入栈
                stack_num.push(token);
            }
        }

        return Integer.parseInt(stack_num.pop());
    }
}
